<?php

namespace App\Http\Controllers\Frontend\V10\UnionLogin;

use App\Library\String\UnionLoginTools;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Constant\SmsTemplate;
use App\Library\String\Strings;
use App\Library\String\Aes;
class ProvincialController extends Controller
{

//    const LOAD_URLS = "https://manage.longloan.cn/#/fish";
    const LOAD_URLS = "https://manage.longloan.cn/#/download";


    /**
     * 撞库返回code
     */

    const HIT_CODE_SUCCESS_NEW = 0; //新用户
    const HIT_CODE_SUCCESS_OLD = 1;//省呗借款老用户
    const HIT_CODE_FAILURE = 2;//调用失败（接口失败、参数错误、验签错误等）

    /**
     * 连登返回code
     */
    const UINON_CODE_SUCCESS = 0; //联合登录成功（返回url）
    const UINON_CODE_FAIL = 1; //获取参数失败
    const UINON_CODE_FAILURE_LOGIN = 2;//验签失败
    const UINON_CODE_SUCCESS_OTHER_OLD = 3;//重复注册
    const UINON_CODE_SUCCESS_OTHER_ERROR = 4;//其他错误



    public function index(Request $request){
//        $data = $request->data;
        $data = [
            "mobile"=>"13799889999",
            "username"=>"张三"
        ];
        //todo 处理data
        $sign = UnionLoginTools::ProvincialSign($data);
        $aes = new Aes();
        $encrpt_data =$aes->encrypt($data);
        var_dump($sign);
        var_dump($encrpt_data);
        $ecrypt =  UnionLoginTools::ProvincialSignCheck($data,$sign);
        var_dump($ecrypt);
    }
    /**
     * Description: 接收省呗用户验证
     * Author: ShengZengGuang
     * DateTime: 2019-03-13 14:43
     * @param Request $request
     * @return mixed
     */
    public function check(Request $request)
    {
        try{
            $rec_data = $data_save['data'] = $request->input('data','');
            $ret_sign = $data_save['sign'] = $request->input('sign', '');
            $missParams = '';
            foreach($data_save as $key=>$value){
                if(!$request->filled($key)){
                    $missParams = $value;
                    break;
                }
            }
            if($missParams){
                $code = self::HIT_CODE_FAILURE;
                $message = '请求参数'.$missParams.'为空';
                return json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);
            }
            //解密
            /*$aes = new Aes();
            $decrypt_data = $aes->decrypt($rec_data);
            $json_data = json_decode($decrypt_data, true);
            var_dump($rec_data);
            var_dump($decrypt_data);
            exit;*/
            //验签
            $has_pass = UnionLoginTools::ProvincialSignProCheck($rec_data,$ret_sign);
            if(!$has_pass){
                $code = self::HIT_CODE_FAILURE;
                $message = '数据签名错误';
                return json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);
            }
            $raw_mobile = $rec_data;
            $userModel = new User();
            $userModel->setConnection('backend');
            $has_register = $userModel->where(['phone_num_md5'=>$raw_mobile])->value('id');
            if($has_register) {
                $code = self::HIT_CODE_SUCCESS_OLD;
                $message = '您是借款老用户';
                return json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);
            }
            $code = self::HIT_CODE_SUCCESS_NEW;
            $message = '新用户';
            return json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);
        }catch (\Exception $e){
            $code = self::HIT_CODE_FAILURE;
            return json_encode(['code'=>$code,'msg'=>$e->getMessage()],JSON_UNESCAPED_UNICODE);
        }
    }
    /**
     * Description: 接收省呗用户注册
     * Author: ShengZengGuang
     * DateTime: 2019-03-13 14:43
     * @param Request $request
     * @return mixed
     */
    public function user_register(Request $request)
    {
        $url = self::LOAD_URLS.'?channel='.User::SOURCE_SHENG_BAI;
        try{
            $rec_data = $data_save['data'] = $request->input('data','');
            $rec_sign = $data_save['sign'] = $request->input('sign', '');
            $missParams = '';
            foreach($data_save as $key=>$value){
                if(!$request->filled($key)){
                    $missParams = $value;
                    break;
                }
            }
            if($missParams){
                $code = self::UINON_CODE_FAIL;
                $message = '请求参数'.$missParams.'为空';
                return json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);
            }
            //解密
            $aes = new Aes();
            $decrypt_data = $aes->decrypt($rec_data);
            $json_data = json_decode($decrypt_data, true);
            //验签
            $has_pass = UnionLoginTools::ProvincialSignCheck($json_data,$rec_sign);
            if(!$has_pass){
                $code = self::UINON_CODE_FAILURE_LOGIN;
                $message = '数据签名错误';
                return json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);
            }
            $mobile = $json_data['mobile'];
//            $username = $json_data['username'];
            if(User::where('phone_num',$mobile)->value('id')){
                $code = self::UINON_CODE_SUCCESS_OTHER_OLD;
                $message = '已注册用户重复注册';
                return json_encode(['code'=>$code,'msg'=>$message,'url'=>$url],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
            }
            $rand_code =Strings::randomCode(6);
            User::createUser([
                'phone_num' => $mobile,
                'password' => $rand_code,
                'source' => User::SOURCE_SHENG_BAI,
            ]);
           // $mobile = '15737893304';
            //推送省呗用户，快闪卡贷自动注册成功
            SmsTemplate::send(SmsTemplate::TEMPLATE_RZG_REGISTER,$mobile,['name'=>$mobile,'password'=>$rand_code]);
            $code = self::UINON_CODE_SUCCESS;
            $message = '成功';
            return json_encode(['code'=>$code,'msg'=>$message,'url'=>$url],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        }catch (\Exception $e){
            $code = self::UINON_CODE_SUCCESS_OTHER_ERROR;
            return json_encode(['code'=>$code,'msg'=>$e->getMessage()],JSON_UNESCAPED_UNICODE);
        }
    }
}
